<template>
  <div class="container">
    <!-- 问题1；新增学科是否显示状态的更改 -->

    <!-- Card 卡片-->
    <el-card class="box-card">
      <!-- 1-搜索区域 -->
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form ref="formRef" label-width="80px">
            <el-form-item label="学科名称">
              <el-input
                placeholder="请输入学科"
                clearable
                v-model.trim="queryInfo.subjectName"
                @clear="getSubjectsList"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>

        <el-col :span="8">
          <el-button @click="clearValue" class="clearbtn">清除</el-button>
          <el-button type="primary" @click="search">搜索</el-button>
        </el-col>
        <el-col :span="8">
          <div class="btn">
            <el-button
              type="success"
              icon="el-icon-edit"
              @click="addSubjectShow = true"
              >新增学科</el-button
            >
          </div>
        </el-col>
      </el-row>

      <!-- 2-警告提示区域 -->
      <el-alert
        :title="`数据一共${counts}条`"
        show-icon
        :closable="false"
        type="info"
      >
      </el-alert>

      <!-- 3、table表格区域 -->
      <el-table
        :data="subjectList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" :index="rowIndex" label="序号">
        </el-table-column>
        <el-table-column prop="subjectName" label="学科名称"> </el-table-column>
        <el-table-column prop="username" label="创建者"> </el-table-column>
        <el-table-column prop="addDate" label="创建日期">
          <template slot-scope="scope">
            {{ scope.row.addDate | parseTimeByString }}
          </template>
        </el-table-column>
        <el-table-column prop="isFrontDisplay" label="前台是否显示">
          <template slot-scope="scope">
            {{ scope.row.isFrontDisplay == true ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="twoLevelDirectory" label="二级目录">
        </el-table-column>
        <el-table-column prop="tags" label="标签" width="100">
        </el-table-column>
        <el-table-column prop="totals" label="题目数量"> </el-table-column>
        <el-table-column prop="address" label="操作" width="260">
          <template slot-scope="scope">
            <el-tag
              type="success"
              size="mini"
              @click="go(scope.row, scope.row.id, scope.row.subjectName)"
              >学科分类</el-tag
            >
            <el-tag
              type="info"
              size="mini"
              @click="gos(scope.row, scope.row.id, scope.row.subjectName)"
              >学科标签</el-tag
            >
            <el-tag size="mini" @click="editSubjectById(scope.row.id)"
              >修改</el-tag
            >
            <el-tag type="danger" size="mini" @click="deleteById(scope.row.id)"
              >删除</el-tag
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 4-分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="counts"
      >
      </el-pagination>
    </el-card>

    <!-- 5-新增学科Dialog 对话框弹出层 -->
    <el-dialog
      @close="addSubjectDialogClose"
      title="新增学科"
      :visible.sync="addSubjectShow"
      width="30%"
    >
      <el-form
        :model="addSubjectNameForm"
        :rules="addSubjectRules"
        ref="addSubjectRef"
        label-width="100px"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input
            v-model="addSubjectNameForm.subjectName"
            placeholder="请输入学科名"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="addSubjectNameForm.isFrontDisplay"
            :active-value="true"
            active-color="#13ce66"
            :inactive-value="false"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addSubjectShow = false">取 消</el-button>
        <el-button type="primary" @click="addSubject">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 6、修改学科对话框 -->
    <el-dialog
      @close="editSubjectDialogClose"
      title="修改学科"
      :visible.sync="editDialogVisible"
      width="30%"
    >
      <el-form
        :model="editSubjectNameForm"
        :rules="editSubjectRules"
        ref="editSubjectRef"
        label-width="100px"
      >
        <el-form-item label="修改学科" prop="subjectName">
          <el-input
            v-model="editSubjectNameForm.subjectName"
            placeholder="请输入学科名"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="editSubjectNameForm.isFrontDisplay"
            :active-value="true"
            active-color="#13ce66"
            :inactive-value="false"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editName">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 7-删除学科的弹出层 MessageBox 弹框-->
  </div>
</template>

<script>
// 1-导入请求学科列表接口
import { list, add, update, detail, remove } from '@/api/hmmm/subjects'

//添加学科接口

export default {
  name: 'add',
  props: {},
  created() {
    //1-初始化请求获取学科列表数据
    this.getSubjectsList()
  },
  data() {
    return {
      //请求携带的参数
      queryInfo: {
        subjectName: '', //查询参数,与搜索框内的值绑定
        page: 1, //当前页码值
        pagesize: 10, //每页显示的条数
      },
      //存储获取的学科列表数据
      subjectList: [],
      //学科总条数,默认0
      counts: 0,

      // 5-控制新增学科弹出层夫人显示与隐藏
      addSubjectShow: false,

      // 新增学科form对象
      addSubjectNameForm: {
        subjectName: '',
        isFrontDisplay: true, //布尔值，新增学科,是否在页面显示 1是 0否
      },
      //新增学科form验证对象
      addSubjectRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
        ],
      },

      // 控制修改学科弹层的显示与隐藏
      editDialogVisible: false,
      //点击查询到的当前学科信息
      editSubjectNameForm: {
        subjectName: '',
        isFrontDisplay: true,
        id: null,
      },
      //修改学科form验证对象
      editSubjectRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
        ],
      },
    
    }
  },
  computed: {
    //计算属性，解决切换页码值，索引初始化升序问题
    rowIndex() {
      //10,  第2页,11
      const beginIndex = (this.queryInfo.page - 1) * this.queryInfo.pagesize + 1
      return beginIndex
    },
  },
  methods: {
    //学科分类跳转
    go(row, id, names) {
       this.fullscreenLoading = true;
        setTimeout(() => {
          this.fullscreenLoading = false;
        }, 2000);
      console.log(row, id, names)
      this.$router.push({
        path: 'directorys',
        query: {
          id: id,
          name: names,
        },
      })
    },
    //学科标签跳转
    gos(row, id, names) { 
      console.log(row, id, names)
      this.$router.push({
        path: 'tags',
        query: {
          id: id,
          name: names,
        },
      })
    },
    //1-请求获取学科列表数据
    async getSubjectsList() {
      try {
        const { data: res } = await list(this.queryInfo)
        console.log(res)
        // this.$message.success("获取学科列表数据成功！");

        //把获取到的数据存储到data中，渲染表格
        this.subjectList = res.items
        console.log(this.subjectList)

        //把获取的总条数赋值给data中的counts
        this.counts = res.counts
      } catch (err) {
        this.$message.error('获取学科列表数据失败！')
      }
    },
    // 1 监听pagesize切换每页显示多少条数据变化，默认显示5条
    handleSizeChange(newPageSize) {
      console.log(`每页 ${newPageSize} 条`)
      //把最新的每页数据 赋值 给 data中的 pagesize
      this.queryInfo.pagesize = newPageSize
      //重新发起请求 渲染 页面
      this.getSubjectsList()
    },
    //2 监听pagenum当前页码值变化,默认显示第1页
    handleCurrentChange(newPageNum) {
      console.log(`当前页: ${newPageNum}`)
      //把最新的当前页码值 赋值 给 data中的pagenum
      this.queryInfo.page = newPageNum
      //重新发起请求 渲染 页面
      this.getSubjectsList()
    },
    // -----------------新增学科区域------------------------
    //点击清除按钮，清空表单内容
    clearValue() {
      this.queryInfo.subjectName = ''
      this.getSubjectsList()
    },
    //点击搜索按钮，根据搜索关键字渲染页面-----问题已解决
    search() {
      if (this.queryInfo.subjectName == '') {
        return this.$message.error('请输入搜索内容！')
      }
      this.getSubjectsList()
    },
    //监听clearDialog关闭事件，重置表单
    addSubjectDialogClose() {
      this.$refs.addSubjectRef.resetFields()
    },

    //点击新增学科，弹出层，请求添加
    addSubject() {
      // console.log(this.addSubjectNameForm);
      //请求新增前，对表单进行预校验
      this.$refs.addSubjectRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) {
          //验证不通过
          return this.$message('您的填写不符合要求')
        }
        //验证通过，请求添加--------------参数问题
        try {
          const { data } = await add({
            subjectName: this.addSubjectNameForm.subjectName,
            isFrontDisplay: this.addSubjectNameForm.isFrontDisplay,
          })
          // console.log(data);
          //关闭弹出层
          this.addSubjectShow = false
          //成功提示
          this.$message.success('新增学科成功')
          //刷新页面
          this.getSubjectsList()
        } catch (err) {
          this.$message.error('添加学科失败！')
          // console.log(err);
        }
        console.log(this.isFrontDisplay)
      })

      //关闭弹出层
      this.addSubjectShow = false
    },

    //---------- 修改学科区域-----------
    //监听修改的关闭事件，重置表单
    editSubjectDialogClose() {
      this.$refs.editSubjectRef.resetFields()
    },

    //请求，根据id，查找点击的需要修改的当前学科
    async editSubjectById(id) {
      console.log(id)
      this.editDialogVisible = true
      try {
        //请求获取当前学科的信息
        const { data: res } = await detail({ id: id })
        console.log(res)
        // 把点击查询到的当前学科信息存储到data内，作为渲染修改框的原始显示内容
        this.editSubjectNameForm.subjectName = res.subjectName
        this.editSubjectNameForm.isFrontDisplay =
          res.isFrontDisplay == 1 ? true : false
        this.editSubjectNameForm.id = res.id
        console.log(this.editSubjectNameForm)
        // this.$message.success("获取当前学科信息成功");
      } catch (err) {
        this.$message.error('获取当前学科信息失败!')
      }
    },

    //发起修改更新请求
    editName() {
      //对表单进行预校验
      this.$refs.editSubjectRef.validate(async (valid) => {
        console.log(this.editSubjectNameForm.id)
        if (!valid) {
          return this.$message('您的填写不符合要求')
        }
        try {
          //验证通过
          const { data: res } = await update({
            subjectName: this.editSubjectNameForm.subjectName,
            isFrontDisplay: this.editSubjectNameForm.isFrontDisplay,
            id: this.editSubjectNameForm.id,
          })
          console.log(res)
          //刷新页面
          this.getSubjectsList()
          //关闭弹层
          this.editDialogVisible = false
          this.$message.success('更新学科信息成功')
        } catch (err) {
          this.$message.error('更新学科信息失败')
        }
      })
      this.editDialogVisible = false
    },

    // 删除学科区域
    async deleteById(id) {
      console.log(id)
      //弹出MessageBox询问框，是否删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该学科, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => {
        return err
      })
      //用户点击取消，得到字符串cancel
      //用户点击确定，得到字符串confirm
      console.log(confirmResult)
      //判断用户是否确定删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除该学科！')
      }
      //发起请求，删除该学科
      try {
        const { data: res } = await remove({
          id: id,
        })
        // console.log(res);
        //更新页面
        this.getSubjectsList()
        this.$message.success('删除成功!')
      } catch (err) {
        this.$message.error('删除该学科失败!')
      }
      //当前页只有一条数据时，删除跳转
      if (this.subjectList.length === 1 && this.queryInfo.page > 1) {
        this.queryInfo.page -= 1 //向前跳一页
        this.getSubjectsList()
      }
    },
  },
}
</script>

<style scoped lang='less'>
.btn {
  float: right !important;
}
.el-tag {
  margin-right: 5px !important;
  cursor: pointer;
}
.el-pagination {
  float: right;
  margin-bottom: 15px;
}
.el-button .el-button--default .el-button--medium {
  border: 1px !important;
}
</style>
